package com.example.demo.activeMQ;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class ConsumerTopic {

    private static final String url = "tcp://127.0.0.1:61616";//actvemq的服务器tcp连接方式
    private static final String topicName = "topic-test";//定义队列的名称

    public static void main(String[] args) throws JMSException {
        //实例化工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        //通过连接工厂来获取连接
        Connection connection = connectionFactory.createConnection();
        //启动连接
        connection.start();
        //创建session,第一个参数为是否开启事务
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //创建消息队列
        Destination destination = session.createTopic(topicName);
        //创建消息生产者
        MessageConsumer comsumer = session.createConsumer(destination);

        comsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage)message;
                try{
                    System.out.println("接收到的消息:"+textMessage.getText());
                }catch(JMSException e){
                    e.printStackTrace();
                }

            }
        });

//        connection.close();

    }
}
